<template>
  <div>
    <div class="flex justify-between items-center mb-2">
      <div class="absolute top-[-9999px] hidden">
        <a-button ref="printLong" v-print="{ id: 'printLong' }">打印</a-button>
        <a-button ref="printSort" v-print="{ id: 'printSort' }">打印</a-button>
        <a-button ref="printBen" v-print="{ id: 'printBen' }">打印</a-button>
        <!-- 打印本 -->
        <PrintViewBen id="printBen" :print-data="printData" :print-type="printType" />
      </div>
      <div class="flex items-center">
        <div class="ml-6">
          计划执行
          <a-range-picker v-model:value="formState.dateRange" class="w-56 ml-2" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="getData" />
        </div>
        <div class="ml-4 flex items-center">
          仅看未执行医嘱 <a-switch v-model:checked="formState.execStatus" class="ml-2" un-checked-value="" :checked-value="0" @change="getData" />
        </div>
        <div v-if="!isShowAllAdvice" class="ml-4 flex items-center">
          查看所有医嘱 <a-switch v-model:checked="formState.showAllAdvice" class="ml-2" @change="getData" />
        </div>
      </div>
      <div class="flex">
        <a-button v-if="getSystemConfig('NAVYHIS_MODE') !== '1'" class="mr-2" @click="onClickPrint"><BaseIcon name="PrinterOutlined" />检查单</a-button>
        <a-dropdown v-if="getSystemConfig('NAVYHIS_MODE') !== '1'" placement="bottom">
          <a-button><BaseIcon name="PrinterOutlined" :loading="printLoading" />执行本</a-button>
          <template #overlay>
            <a-menu @click="onPrintBen">
              <a-menu-item key="1" value="1"> 注射本 </a-menu-item>
              <!-- <a-menu-item key="0" value="1"> 静脉本 </a-menu-item> -->
              <a-menu-item key="2" value="2"> 治疗本 </a-menu-item>
              <a-menu-item key="3" value="3"> 口服本 </a-menu-item>
              <a-menu-item key="4" value="4"> 滴眼液本 </a-menu-item>
              <a-menu-item key="5" value="5"> 护理单 </a-menu-item>
              <!-- <a-menu-item key="6" value="6"> 核对单 </a-menu-item> -->
            </a-menu>
          </template>
        </a-dropdown>
        <a-button type="primary" class="ml-2" @click="onBatchExec">批量执行</a-button>
      </div>
    </div>
    <BaseTable
      fill
      column-code="00001083"
      :loading="loading"
      :data-source="tableData"
      :exclude-columns="['action']"
      :row-selection="{
        selectedRowKeys,
        getCheckboxProps: (record) => ({
          disabled:
            record.isChid ||
            record.execNurseStatus !== 0 ||
            record.execStatus === 4 ||
            record.execStatus === 3 ||
            (!isShowAllAdvice && record.ksdm && userStore.ksdm !== record.ksdm)
        }),
        onChange: onSelectChange
      }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'xh'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'brName'">
          <span>{{ record.brName }}</span>
          <span class="ml-4">{{ record.brXb }}</span>
          <span class="ml-4">{{ record.brAge }}</span>
        </template>
        <template v-if="column.dataIndex === 'execStatus'">
          <!-- execStatus：执行状态  0：待执行(非药品) 1：已执行 2：待执行（已发药）3：已退药 4：退药中   -->
          <a-tag v-if="record.execStatus === 0" color="blue">已申请</a-tag>
          <a-tag v-if="record.execStatus === 1" color="success">已执行</a-tag>
          <!-- <a-tag v-if="record.execStatus === 0" color="blue">
            <span v-if="!record.ksdm || record.ksdm === userStore.ksdm">已申请</span>
            <span v-else>{{ isShowAllAdvice && record.execNurseStatus === 1 ? '已执行' : '已申请' }}</span>
          </a-tag>
          <a-tag v-if="record.execStatus === 1" color="blue">
            <span v-if="!record.ksdm || record.ksdm === userStore.ksdm">已执行</span>
            <span v-else>{{ isShowAllAdvice && record.execNurseStatus === 0 ? '已申请' : '已执行' }}</span>
          </a-tag> -->
          <a-tag v-if="record.execStatus === 2" color="blue">{{ isDrug(record.advTypeCode) ? '已发药' : '已申请' }}</a-tag>
          <a-tag v-if="record.execStatus === 3" color="green">已退药</a-tag>
          <a-tag v-if="record.execStatus === 4" color="red">退药中</a-tag>
        </template>
        <template v-if="column.dataIndex === 'execNurseStatus'">
          <a-tag v-if="record.execNurseStatus === 0" color="blue">未执行</a-tag>
          <a-tag v-if="record.execNurseStatus === 1" color="success">已执行</a-tag>
        </template>
        <template v-if="column.dataIndex === 'children'">
          <template v-if="record.advOrderType === 0">
            <DoctorAdviceOrder
              :row-data="record"
              :params-key="{
                mc: 'adv.mc',
                gg: 'adv.gg',
                sl: 'clinicalDose',
                dw: 'adv.jldw',
                yf: 'deliverRoute.fyff',
                pl: 'fqy.plid',
                drugPathName: 'drugPathName'
              }"
            />
          </template>
          <template v-else>
            <div class="pl-2">
              <a-tooltip>
                <template #title>{{ record?.advName }}</template>
                {{ record?.advName }}
              </a-tooltip>
            </div>
          </template>
        </template>
        <template v-if="column.dataIndex === 'yzzxlb'">
          {{ record.yzzxlb == 0 ? '临时' : '长期' }}
        </template>
      </template>
    </BaseTable>
    <ExpenseQuery v-model:open="expenseQueryOpen" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import BaseTable from '@/components/BaseTable'
import { getSystemConfig } from '@/utils/systemConfig'
import useUserStore from '@/store/user'
import useStore from '../store'
import ExpenseQuery from './ExpenseQuery'
import PrintViewBen from './print/PrintViewBen'

const userStore = useUserStore()
const expenseQueryOpen = ref(false)
const printLoading = ref(false)
const store = useStore()
const selectedRowKeys = ref([])
const selectedRows = ref([])
const printData = ref({})
const printLong = ref()
const printSort = ref()
const printBen = ref()
const formState = ref({
  execStatus: 0,
  showAllAdvice: false,
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})

const { tableData, getData, loading } = useTable({
  url: '/inp/clinicalOrder/getClinicalOrderExecuteList',
  pagination: false,
  formatParams: () => {
    return {
      ...store.searchState,
      pyjm: store.searchState.zjm,
      showAllAdvice: isShowAllAdvice ? true : formState.value.showAllAdvice,
      // execStatus: formState.value.execStatus,
      execNurseStatus: formState.value.execStatus,
      startTime: formState.value.dateRange[0],
      endTime: formState.value.dateRange[1]
    }
  },
  onSuccess: () => {
    store.loading = false
    selectedRowKeys.value = []
    selectedRows.value = []
  }
})

const onSelectChange = (keys, rows) => {
  selectedRowKeys.value = keys
  selectedRows.value = rows
}

const printType = ref('1')

const onPrintBen = async (e) => {
  printLoading.value = true
  if (e.item.value !== '5' && e.item.value !== '6') {
    const { code, msg, data } = await post('/inp/Print/printOralBenDoctorOrders', {
      clinicalOrderListList: tableData.value.map((item) => ({ advId: item.advId })),
      reportType: e.item.value,
      bqbh: store.searchState.bqid,
      inpAdvice: store.searchState.inpAdvice,
      startTime: formState.value.dateRange[0],
      endTime: formState.value.dateRange[1]
    })
    printLoading.value = false
    if (code !== 0) return message.error(msg || '获取打印数据失败')
    if (getSystemConfig('NAVYHIS_MODE') === '1') {
      printType.value = e.item.value
      printData.value = JSON.parse(data)
      if (!printData.value.printData.detail?.length) return message.error('没有需要打印的数据')
      setTimeout(() => {
        printBen.value.$el.click()
      }, 1000)
    } else {
      window.openExe?.rpt(data) //调用winform打印
    }
  } else {
    if (e.item.value === '5') {
      const { code, msg, data } = await post('/inp/Print/printHLD', { wardId: store.searchState.bqid })
      printLoading.value = false
      if (code !== 0) return message.error(msg || '获取打印数据失败')
      window.openExe?.rpt(data) //调用winform打印
    } else {
      const { code, msg, data } = await post('/inp/Print/printHDD', { wardId: store.searchState.bqid })
      printLoading.value = false
      if (code !== 0) return message.error(msg || '获取打印数据失败')
      window.openExe?.rpt(data) //调用winform打印
    }
  }
}
// 打印检查单
const onClickPrint = async () => {
  const arrIds = tableData.value?.map((item) => {
    return item.id
  })
  const { code, msg, data } = await post('/inp/Print/printJCD', {
    ...store.searchState,
    pyjm: store.searchState.zjm,
    execStatus: formState.value.execStatus,
    startTime: formState.value.dateRange[0],
    endTime: formState.value.dateRange[1],
    ids: arrIds
  })
  if (code !== 0) return message.error(msg || '获取打印数据失败')
  window.openExe?.rpt(data) //调用winform打印
}
// 获取包括子医嘱的id
const extractIds = (data) => {
  return data.reduce((ids, item) => {
    if (item.id !== undefined) {
      ids.push(item.id)
    }
    if (item.children) {
      ids.push(...extractIds(item.children))
    }
    return ids
  }, [])
}
//执行
const onBatchExec = async () => {
  if (selectedRows.value.length === 0) return message.warning('请先勾选医嘱单')
  const arrId = extractIds(selectedRows.value)
  const res = await post('/inp/clinicalOrder/doNurseExecuteClinicalOrder', {
    zxyzids: arrId,
    execStatus: 1,
    execNurseStatus: 1
  })
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success('操作成功')
  selectedRowKeys.value = []
  selectedRows.value = []
  getData()
}
const isDrug = (code) => {
  // advTypeCode  2,4,5为药品别的为非药品
  if (code === 2 || code === 4 || code === 5) {
    return true
  } else {
    return false
  }
}
const isShowAllAdvice = getSystemConfig('INP_NURSE_EXECUTE_ALL_ADVICE') === '0'
onMounted(() => getData())
//暴露getData
defineExpose({
  getData
})
</script>
